class MyStorageManage {

    /**
     * 从缓存中获取数据
     * @param  key
     */
    getStorage(key) {
        //从缓存中读取
        let data = {}
        if (key && this._isReadOrSetStorage(key)) {
            data = wx.getStorageSync(key)
        }
        return data
    }


    /**
     * 获取缓存
     * @param String $key  key
     * @param String $def  若想要无缓存时，返回默认值则get('key','默认值')（支持字符串、json、数组、boolean等等）
     * @return value;
     */
    getStorage(key, def = '') {
        let data = def;
        if (key && this._isReadOrSetStorage(key)) {
            let timeout = parseInt(wx.getStorageSync(`${key}__separator__`) || 0);
            // 过期失效
            if (timeout) {
                if (Date.now() > timeout) {
                    this._remove(key);
                    return;
                }
            }
            data = wx.getStorageSync(key)
        }
        return data;
    }

    setStorage(key, value) {
        if (this._isReadOrSetStorage(key)) {
            wx.setStorage({
                data: value,
                key: key
            })
        }
    }


    /**
     * 设置缓存
     * @param String $key       key
     * @param String $value     value（支持字符串、json、数组、boolean等等）
     * @param Number $timeout   过期时间（单位：分钟）不设置时间即为永久保存
     * @return value;
     */
    setStorage(key, value, timeout = 0) {
        if (key && this._isReadOrSetStorage(key)) {
            let _timeout = timeout ==0 ?this._gettimeout(key):parseInt(timeout);
            wx.setStorageSync(key, value);
            if (timeout) {
                wx.setStorageSync(`${key}__separator__`, Date.now() + 1000 * 60 * _timeout);
            } else {
                wx.removeStorageSync(`${key}__separator__`);
            }
            return value;
        }
    }
    /**
     * 根据key值返回默认时间
     * @param {*} key
     */
    _gettimeout(key){
        //默认30分钟
        let time = 30;
        return time
    }

    /**
     * 判断是否从缓存中读取或者将数据存储到缓存中
     * @param {} url
     */

    _remove(key) {
        wx.removeStorageSync(key);
        wx.removeStorageSync(`${key}__separator__`);
    }

    _isReadOrSetStorage(url) {
        return true;
    }

}

export {MyStorageManage}